package com.park.user.controller.callback;

import com.github.wxpay.sdk.WXPayUtil;
import com.park.comm.ParkEnum;
import com.park.controller.BaseController;
import com.park.dao.mapper.notice.OrderNoticeMapper;
import com.park.dao.mapper.order.ParkOrderInfoMapper;
import com.park.dao.mapper.user.UserMapper;
import com.park.entity.notice.OrderNotice;
import com.park.entity.order.ParkOrderInfo;
import com.park.entity.park.ParkInfo;
import com.park.entity.user.UserInfo;
import com.park.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.Map;

/**
 * @author ZhangHaiWen
 * @title: WxCallbackController
 * @projectName park
 * @description: 微信支付回调
 * @date 2020/5/823:11
 */
@Slf4j
@RestController
@RequestMapping(value = "/wx/pay")
public class WxCallbackController extends BaseController {

    @Autowired
    private ParkOrderInfoMapper parkOrderInfoMapper;

    @Autowired
    private OrderNoticeMapper orderNoticeMapper;

    // {transaction_id=4200000532202005092814739851,
    // nonce_str=6c59069991c243eea595063fa17b1506,
    // bank_type=OTHERS, openid=oygRA5WPnqWRsl-FKvk2cgWWZm7Q,
    // sign=16A4B0ED08F2DA9A3A485B69A4C8A900, fee_type=CNY,
    // mch_id=1591427241, cash_fee=1,
    // out_trade_no=9259fd64a4084c73b1a42ccfd4bde069,
    // appid=wx712921d806a78fec,
    // total_fee=1,
    // trade_type=JSAPI,
    // result_code=SUCCESS,
    // time_end=20200509012528,
    // is_subscribe=N,
    // return_code=SUCCESS}
    //微信支付回调
    @RequestMapping(value = "/callback",method = RequestMethod.POST)
    public Result addLicenseplate(){
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String resultxml = new String(outSteam.toByteArray(), "utf-8");
            //转为map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultxml);
            String return_code = resultMap.get("return_code");
            String result_code = resultMap.get("result_code");
            if("SUCCESS".equals(return_code)){
                if("SUCCESS".equals(result_code)){
                    String orderNo = resultMap.get("out_trade_no");
                    log.info("支付成功回调中的orderNo,{}",orderNo);
                    //根据订单号查询订单 更新订单表的状态
                    ParkOrderInfo parkOrderInfo = parkOrderInfoMapper.getOrerByOrderNo(orderNo);
                    if(!parkOrderInfo.getOrderStatus().equals(ParkEnum.PARK_STATUS_FINISH.status)){
                        //将信息插入订单通知表
                        OrderNotice orderNotice = new OrderNotice();
                        orderNotice.setOrderId(parkOrderInfo.getId());
                        orderNotice.setParkId(parkOrderInfo.getParkId());
                        orderNotice.setUserId(parkOrderInfo.getUserId());
                        orderNotice.setLicensePlate(parkOrderInfo.getOrderLicense());
                        orderNotice.setParkName(parkOrderInfo.getParkName());
                        orderNotice.setIsCalbackNotice(0);
                        long timeMillis = System.currentTimeMillis();
                        orderNotice.setAddTimeStamp(timeMillis);
                        orderNotice.setTimeStamp(timeMillis);
                        orderNotice.setOrderTotle(parkOrderInfo.getOrderTotal());
                        orderNoticeMapper.insert(orderNotice);
                    }
                    long timeMillis = System.currentTimeMillis();
                    parkOrderInfo.setOrderPayStatus(ParkEnum.ORDER_PAY_STATUS_PAYED.status);
                    parkOrderInfo.setOrderStatus(ParkEnum.PARK_STATUS_FINISH.status);
                    parkOrderInfo.setOrderEndStamp(timeMillis);
                    parkOrderInfo.setTimeStamp(timeMillis);
                    parkOrderInfoMapper.updateByPrimaryKeySelective(parkOrderInfo);
                }
            }
            log.info("微信支付回调 ： "+ resultMap);
            response.reset();
            OutputStream  outputStream = response.getOutputStream();
            outputStream.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>".getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS();
    }

}
